package cate.game.pvp.pointrace.handler;

import cate.game.pvp.pointrace.data.PointRaceRankRwd;
import cate.game.pvp.pointrace.data.PointRaceRankRwdData;
import org.apache.commons.compress.utils.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

public class BothPointRaceRankRwdOperation implements PointRaceRankRwdOperation {

    private final PointRaceRankRwdData rankRwdData;

    public BothPointRaceRankRwdOperation(Supplier<PointRaceRankRwdData> rankRwdDataSupplier) {
        this.rankRwdData = Objects.requireNonNull(rankRwdDataSupplier.get());
    }

    @Override
    public void upsert(List<PointRaceRankRwd> rankRwdList) {
        for (PointRaceRankRwd rankRwd : rankRwdList) {
            if (!rankRwdData.contains(rankRwd.getSrvIdIndexName(), rankRwd.getIndexedKey())) {
                rankRwdData.addValue(rankRwd);
                rankRwdData.addIndex(rankRwd.getSrvIdIndexName(), rankRwd.getIndexedKey(), rankRwd);
            }
        }
    }

    @Override
    public List<PointRaceRankRwd> query(QueryParam param) {
        Map<String, PointRaceRankRwd> indexMap = rankRwdData.getIndex(param.getIndexedKey());
        return Objects.nonNull(indexMap) ?
                new ArrayList<>(indexMap.values())
                : Lists.newArrayList();
    }
}
